package com.brillilab.message.handler;

import com.alibaba.fastjson.JSONObject;
import com.brillilab.common.rocketmq.UsersCacheVo;
import com.brillilab.domain.enums.common.BoolEnum;
import com.brillilab.domain.po.message.Message;
import com.brillilab.message.core.AppMessageSender;
import com.brillilab.message.core.SocketMessageSender;
import com.brillilab.message.vo.AppMessageVo;
import com.brillilab.message.vo.SocketMessageVo;
import com.brillilab.service.core.message.IMessageService;
import com.brillilab.service.logic.user.UsersLogic;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Component
public class MessageHandler {

    @Resource
    private AppMessageSender appMessageSender;
    @Resource
    private SocketMessageSender socketMessageSender;
    @Resource
    private IMessageService messageService;
    @Resource
    private UsersLogic usersLogic;

    public static Integer AIO = 1;
    public static Integer APP = 2;

    public void handler(String messageData,Integer type) {
        boolean success = false;

        if(AIO.equals(type)){
            SocketMessageVo socketMessageVo = socketMessageSender.buildMessageVo(messageData);
            success = socketMessageSender.sendMessage(socketMessageVo);
        }

        if(APP.equals(type)){
            AppMessageVo appMessageVo=appMessageSender.buildMessageVo(messageData);
            if (StringUtils.isNotBlank(appMessageVo.getAccount())){
                String[] accounts = appMessageVo.getAccount().split(",");
                if (accounts.length>100){
                    success=appMessageSender.sendMessageMoreThan100(appMessageVo);
                }else {
                    success=appMessageSender.sendMessage(appMessageVo);
                }
            }
        }

        if (success) {
            Message message =JSONObject.parseObject(messageData,Message.class);
            if(message.getId()!=null && message.getId()>0) {
                message.setSuccess(BoolEnum.TRUE.getValue());
                message.setSendTime(new Date());
                messageService.update(message);
            }
        }
    }

    public void handler(String title, List<String> deviceNos, Object data) {
        SocketMessageVo socketMessageVo = socketMessageSender.buildMessageVo(title, JSONObject.toJSONString(data), deviceNos);
        socketMessageSender.sendMessage(socketMessageVo);
    }

    public void handlerModifyUserCache(UsersCacheVo userCacheVo) {
        //更新用户缓存
        usersLogic.setRefreshUser(userCacheVo.getLabMemberId(),userCacheVo.getMessage(),userCacheVo.isToCenter());
    }
}
